package org.fuxia.im.gui;

import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;

import org.fuxia.im.common.ClientConst;
import org.fuxia.im.common.ClientContext;
import org.fuxia.im.common.CommonDialog;
import org.fuxia.im.common.LocationUtil;
import org.fuxia.im.common.MyListCellModel;
import org.fuxia.im.common.MyListCellModel.ShowUser;
import org.fuxia.im.common.MyListCellRender;
import org.fuxia.im.core.ECMessageType;
import org.fuxia.im.core.entries.ECPacket;
import org.fuxia.im.core.utils.ObjectUtil;
import org.tony.common.ui.CommonFrame;

import com.alibaba.fastjson.JSONArray;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class GroupManager extends CommonFrame {

	private static final long serialVersionUID = -6152515529728908109L;
	private static final Font BORDER_FONT =  new Font("微软雅黑", Font.BOLD, 12); 
	private static final Font COMMON_FONT = new Font("微软雅黑", Font.PLAIN, 12) ;
	
	private JPanel contentPane;
	private JTextField groupName;
	private JTable selectedUser;
	private JList userList ;


	
	public GroupManager() {
		super();
		setResizable(false);
		setTitle("\u521B\u5EFA\u7FA4\u7EC4");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setSize(537, 400);
		setLocation(LocationUtil.getCenterLocationOnScreen(getWidth(), getHeight())) ;
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContent(contentPane);
		GridBagLayout gbl = new GridBagLayout();
		gbl.columnWidths = new int[]{120, 24, 232, 135, 0};
		gbl.rowHeights = new int[]{25, 198, 0};
		gbl.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
		gbl.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
		contentPane.setLayout(gbl);
		
		JLabel groupNameLab = new JLabel("\u7FA4\u7EC4\u540D\u79F0:");
		groupNameLab.setFont(COMMON_FONT);
		GridBagConstraints gbc_groupNameLab = new GridBagConstraints();
		gbc_groupNameLab.anchor = GridBagConstraints.EAST;
		gbc_groupNameLab.insets = new Insets(0, 0, 5, 5);
		gbc_groupNameLab.gridx = 0;
		gbc_groupNameLab.gridy = 0;
		contentPane.add(groupNameLab, gbc_groupNameLab);
		
		groupName = new JTextField();
		GridBagConstraints gbc_groupName = new GridBagConstraints();
		gbc_groupName.fill = GridBagConstraints.HORIZONTAL;
		gbc_groupName.insets = new Insets(0, 0, 5, 5);
		gbc_groupName.gridwidth = 2;
		gbc_groupName.gridx = 1;
		gbc_groupName.gridy = 0;
		contentPane.add(groupName, gbc_groupName);
		groupName.setColumns(10);
		
		JButton create = new JButton("\u521B\u5EFA\u7FA4\u7EC4");
		create.setFont(COMMON_FONT);
		GridBagConstraints gbc_create = new GridBagConstraints();
		gbc_create.anchor = GridBagConstraints.NORTHWEST;
		gbc_create.insets = new Insets(0, 0, 5, 0);
		gbc_create.gridx = 3;
		gbc_create.gridy = 0;
		contentPane.add(create, gbc_create);
		create.addActionListener(new ActionListener() {
			
			public void actionPerformed(ActionEvent e) {
				final String gName = groupName.getText() ;
				if(gName=="" || gName.length()==0){
					JOptionPane.showMessageDialog(getThis(), "群组名称必须填写", "错误信息", JOptionPane.ERROR_MESSAGE) ;
					return ;
				}
				SwingUtilities.invokeLater(new Runnable() {
					public void run() {
						JDialog dia = CommonDialog.createModelWaitDialog(getThis());
						ClientContext.putValue(ClientConst.CURRENT_WAITING_DIALOG, dia);
						ClientContext.putValue(ClientConst.CURRENT_REQUESTOR, getThis()) ;
						ECPacket packet = new ECPacket() ;
						String selfCode =  ClientContext.getLoginUser().getUserCode() ;
						String selfName =  ClientContext.getLoginUser().getNickName() ;
						packet.setMessageType(ECMessageType.CREATE_GROUP.name());
						packet.addParam("groupName", gName);
						packet.addParam("owner",selfCode) ;
						packet.setFrom(ClientContext.getLoginUser().getUserCode()) ;
						int rowCount = selectedUser.getModel().getRowCount();
						List<Object[]> members = new ArrayList<Object[]>();
						members.add(new Object[]{selfCode,selfName});
						for(int i=0;i<rowCount;i++) {
							String userCode = selectedUser.getModel().getValueAt(i, 0).toString();
							String nickName = selectedUser.getModel().getValueAt(i, 1).toString();
							members.add(new Object[]{userCode,nickName});
						}
						String jsonStr = ObjectUtil.getJsonStr(members);
						packet.addParam("members", jsonStr) ;
						try {
							ClientContext.getContext().getClient().sendMessage(packet);
							dia.setVisible(true);
						} catch (Exception e) {
							JOptionPane.showMessageDialog(getThis(), "网络连接失败", "错误信息", JOptionPane.ERROR_MESSAGE) ;
						}
 					}
				});
				
			}
		});
		
		JScrollPane userListScroll = new JScrollPane();
		userListScroll.setBorder(new TitledBorder(null, "用户列表", TitledBorder.LEADING, TitledBorder.TOP, BORDER_FONT, null));
		GridBagConstraints gbc_scrollPane_1 = new GridBagConstraints();
		gbc_scrollPane_1.fill = GridBagConstraints.BOTH;
		gbc_scrollPane_1.insets = new Insets(0, 0, 0, 5);
		gbc_scrollPane_1.gridwidth = 2;
		gbc_scrollPane_1.gridx = 0;
		gbc_scrollPane_1.gridy = 1;
		gbc_scrollPane_1.weighty = 1 ;
		contentPane.add(userListScroll, gbc_scrollPane_1);
		userListScroll.setBackground(UIManager.getColor("Button.background"));
		
		userList = new JList();
		userList.setCellRenderer(new MyListCellRender()) ;
		userList.setFont(COMMON_FONT);
		userList.setBorder(new EmptyBorder(new Insets(0,0,0,0)));
		userListScroll.setViewportView(userList);
		userList.setBackground(UIManager.getColor("Button.background"));
		userList.addMouseListener(new MouseAdapter() {

			public void mouseClicked(MouseEvent e) {
				if(e.getClickCount()==1) {
					int index = userList.getSelectedIndex() ;
					ShowUser user = (ShowUser)userList.getModel().getElementAt(index);
					if(user.isSelected()){
						user.setSelected(false);
						removeRow(user) ;
					}else{
						addRow(user) ;
						user.setSelected(true);
					}
					userList.repaint();
					selectedUser.repaint() ;
				}
				
			}
			
		}) ;
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBorder(new TitledBorder(null, "已选用户", TitledBorder.LEADING, TitledBorder.TOP, BORDER_FONT, null));
		scrollPane.setEnabled(true);
		GridBagConstraints gbc_scrollPane = new GridBagConstraints();
		gbc_scrollPane.fill = GridBagConstraints.BOTH;
		gbc_scrollPane.gridwidth = 2;
		gbc_scrollPane.gridx = 2;
		gbc_scrollPane.gridy = 1;
		gbc_scrollPane.weighty = 1 ;
		gbc_scrollPane.weightx = 1;
		contentPane.add(scrollPane, gbc_scrollPane);
		
		selectedUser = new JTable();
		selectedUser.setFont(COMMON_FONT);
		selectedUser.setBorder(new EmptyBorder(new Insets(0,0,0,0)));
		selectedUser.setModel(new DefaultTableModel(
			new Object[][] {},
			new String[] {
				"用户账户", "用户昵称"
			}
		));
		selectedUser.getColumnModel().getColumn(0).setPreferredWidth(169);
		selectedUser.getColumnModel().getColumn(1).setPreferredWidth(198);
		selectedUser.setEnabled(false);
		scrollPane.setViewportView(selectedUser);
	}
	
	private JFrame getThis(){
		return this ;
	}
	
	private int findRowIndex(ShowUser user) {
		int index = -1 ;
		int rowCount = selectedUser.getModel().getRowCount() ;
		for(int i=0;i<rowCount;i++) {
			if(selectedUser.getModel().getValueAt(i, 0).toString().equals(user.getUserCode())) {
				index = i ;
				break;
			}
		}
		return index ;
	}
	
	private void removeRow(ShowUser user){
		int index = findRowIndex(user);
		if(index==-1){
			return ;
		}
		DefaultTableModel dtm = (DefaultTableModel)selectedUser.getModel();
		dtm.removeRow(index);
	}
	
	private void addRow(ShowUser user){
		DefaultTableModel dtm = (DefaultTableModel)selectedUser.getModel();
		dtm.addRow(new Object[]{user.getUserCode(),user.getNickName()});
	}
	
	public void showDialog(){
		Map friedns = ClientContext.getValue(ClientConst.FRIENDS,Map.class);
		Iterator<Map.Entry> iter = friedns.entrySet().iterator() ;
		MyListCellModel mlc = new MyListCellModel() ;
		while(iter.hasNext()){
			List<JSONArray> values = (List<JSONArray>)iter.next().getValue();
			for(JSONArray d:values){
				mlc.addObject(new Object[]{d.getString(0),d.getString(1)}) ;
			}
		}
		userList.setModel(mlc);
		setVisible(true);
	}
}
